<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Librarian Extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->page_auth->secure_page('librarian');

		$this->load->model('M_enrollees');
		$this->load->model('M_employees');
		$this->_init_pagnate_config();
		$this->view_data['use_bootstrap3'] = true;
	}

	public function index()
	{
		redirect('librarian/students');
	}

	public function students($page = 0)
	{
		$this->view_data['usertype'] = 'students';

		$filter = false;
		$like = false;
		$order_by = false;
		
		$filter['enrollments.e_archived'] = 0;
		$filter['enrollments.registrar_approved'] = 1;
		$filter['enrollments.e_ay_id'] = $this->current_school_year;
		$filter['enrollments.verified'] = 1;
		
		
		$arr_filters = array();
		$suffix = "";
		
		/* GET SEARCH KEYWORDS AND ADD TO FILTER */
		if($_GET)
		{	
			if(isset($_GET['search_param']) && trim($_GET['search_param']) == 'all'){
				$this->view_data['search_param'] = $keyfield = trim($_GET['search_param']);
			}else{

				if(isset($_GET['search_param'])){
					$this->view_data['search_param'] = $keyfield = trim($_GET['search_param']);
					$this->view_data['keyword'] = $keyword = trim($_GET['keyword']); 
					
					if(trim($keyword)){ 
						
						if($keyfield == 'last_name'){ $like['profiles.lastname'] = $keyword; }
						if($keyfield == 'middle_name'){ $like['profiles.middlename'] = $keyword; }
						if($keyfield == 'first_name'){ $like['profiles.firstname'] = $keyword; }
						if($keyfield == 'student_id'){ $like['enrollments.e_student_id'] = $keyword; }
					}
				}
			}
		}
		
		//CONFIGURATION
		$get['fields'] = array(
				'enrollments.e_id as enrollment_id',
				'enrollments.e_student_id as student_id',
				'block_section.block_name',
				'sections.section_name',
				"concat_ws('',profiles.lastname,' , ',profiles.firstname,' ',profiles.middlename) as fullname",
				'levels.level_desc' 
		);
		
		$get['where'] = $filter;
		$get['like'] = $like;
		$get['join'] = array(
			
			1 => array(
				"table" => "profiles",
				"on"	=> "enrollments.e_profile_id = profiles.profile_id",
				"type"  => "LEFT"
			),
			2 => array(
				"table" => "levels",
				"on"	=> "enrollments.e_grade_level = levels.level_id",
				"type"  => "LEFT"
			),
			3 => array(
				"table" => "block_section",
				"on"	=> "enrollments.block = block_section.id",
				"type"  => "LEFT"
			),
			4 => array(
				"table" => "sections",
				"on"	=> "enrollments.e_section_id = sections.id",
				"type"  => "LEFT"
			)
		);

		/* GET STUDENTS WITH PAYMENTS TOTAL OF */
		$paid_ids = $this->M_enrollees->get_paidstudent_inarray();
		if($paid_ids){ 
			$get['in'] = array(
				"field" => "enrollments.e_id",
				"data" => $paid_ids
			);
		} // and e_id IN (IDS)
		$get['order'] = "profiles.lastname";
		$get['all'] = true; //GET ALL EXCLUDE LIMIT
		$get['count'] = true; //RETURN COUNT NOT ROW
		$get['array'] = false; //RETURN OBJECT NOT ARRAY
		$get['single'] = false; //RETURN ALL NOT SINGLE
		
	
		$this->load->library("pagination");
		$config = $this->pagnate_config;
		$config["base_url"] = base_url() ."librarian/students";
		$suffix = '?'.http_build_query($_GET, '', "&");
		$suffix = str_replace("&submit=Search", "", $suffix);
		$config['suffix'] = $suffix;
		$config['first_url'] = $config['base_url'].$config['suffix']; 
		
		$this->view_data['total_rows'] = $config["total_rows"] = $this->M_enrollees->get_record("enrollments", $get);
		
		$config["per_page"] = 30;
		$config['num_links'] = 10;
		$config["uri_segment"] = 3;
		// $config['use_page_numbers'] = TRUE;
		$this->pagination->initialize($config);
		
		//FOR PAGINATION
		$get['all'] = false;
		$get['count'] = false;
		$get['start'] = $page;
		$get['limit'] = $config['per_page'];
		
		$this->view_data['search'] = $search = $this->M_enrollees->get_record("enrollments", $get);
		$this->view_data['links'] = $this->pagination->create_links();
	}	

	public function employees($page = 0)
	{
		$this->view_data['usertype'] = 'employees';	

		$filter = false;
		$like = false;
		$order_by = false;
		
		$filter['employees.userStatus'] = 'active';
		
		$arr_filters = array();
		$suffix = "";
		
		/* GET SEARCH KEYWORDS AND ADD TO FILTER */
		if($_GET)
		{	
			if(isset($_GET['search_param']) && trim($_GET['search_param']) == 'all'){
				$this->view_data['search_param'] = $keyfield = trim($_GET['search_param']);
			}else{

				if(isset($_GET['search_param'])){
					$this->view_data['search_param'] = $keyfield = trim($_GET['search_param']);
					$this->view_data['keyword'] = $keyword = trim($_GET['keyword']); 
					
					if(trim($keyword)){ 
						
						if($keyfield == 'last_name'){ $like['employees.last_name'] = $keyword; }
						if($keyfield == 'middle_name'){ $like['employees.middle_name'] = $keyword; }
						if($keyfield == 'first_name'){ $like['employees.first_name'] = $keyword; }
						if($keyfield == 'student_id'){ $like['employees.given_id'] = $keyword; }
					}
				}
			}
		}
		
		//CONFIGURATION
		$get['fields'] = array(
				'employees.emp_id',
				'employees.given_id as username',
				'employees.role',
				"concat_ws('',employees.last_name,' , ',employees.first_name,' ',employees.middle_name) as fullname",
		);
		
		$get['where'] = $filter;
		$get['like'] = $like;
		
		$get['order'] = "employees.last_name";
		$get['all'] = true; //GET ALL EXCLUDE LIMIT
		$get['count'] = true; //RETURN COUNT NOT ROW
		$get['array'] = false; //RETURN OBJECT NOT ARRAY
		$get['single'] = false; //RETURN ALL NOT SINGLE
		
	
		$this->load->library("pagination");
		$config = $this->pagnate_config;
		$config["base_url"] = base_url() ."librarian/students";
		$suffix = '?'.http_build_query($_GET, '', "&");
		$suffix = str_replace("&submit=Search", "", $suffix);
		$config['suffix'] = $suffix;
		$config['first_url'] = $config['base_url'].$config['suffix']; 
		
		$this->view_data['total_rows'] = $config["total_rows"] = $this->M_employees->get_record(false, $get);
		
		$config["per_page"] = 30;
		$config['num_links'] = 10;
		$config["uri_segment"] = 3;
		// $config['use_page_numbers'] = TRUE;
		$this->pagination->initialize($config);
		
		//FOR PAGINATION
		$get['all'] = false;
		$get['count'] = false;
		$get['start'] = $page;
		$get['limit'] = $config['per_page'];
		
		$this->view_data['search'] = $search = $this->M_employees->get_record(false, $get);
		$this->view_data['links'] = $this->pagination->create_links();
	}
	
	public function media()
	{
		$this->load->model('M_librarian','ml');
		$this->view_data['system_message'] = $this->session->flashdata('system_message');
		/* pagenation */
		$this->load->library('pagination');
		$config = $this->pagnate_config;
		$config['base_url'] = base_url().'librarian/media';
		$config['per_page'] = 15;
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		if($this->input->post('search_books'))
		{
			$search_string = $this->input->post('search');
			$total_rows = $this->ml->count_all_media($search_string);
			if($total_rows > 100)
			{
				$this->view_data['system_message'] = $this->_msg('n',"Fetched a  total of ({$total_rows}) Books. You might want to add more information on your search string.");
			}else{
				$this->view_data['media'] = $this->ml->fetch_media($search_string);
				$this->view_data['system_message'] = $this->_msg('n',"Fetched a total of ({$total_rows}) Book(s) that fit your search description.");
			}
		}else{
			$config['total_rows'] = $this->ml->count_all_media();
			$this->view_data['media'] = $this->ml->fetch_media(FALSE,$config["per_page"], $page);
			$this->pagination->initialize($config);
		}
		// vd($this->db->last_query());
        $this->view_data["links"] = $this->pagination->create_links();
	}
	
	public function categories()
	{
		$this->load->model('M_librarian','ml');
		$this->view_data['system_message'] = $this->session->flashdata('system_message');
		/* pagenation */
		$this->load->library('pagination');
		$config['base_url'] = base_url().'librarian/categories';
		$config['total_rows'] = $this->ml->count_all_categories();
		$config['per_page'] = 15;
		$config['full_tag_open'] = '<div class="pagnate-links">';
		$config['full_tag_close'] = '</div>';
		$config['first_link'] = 'First';
		$config['last_link'] = 'Last';
		$config['next_link'] = 'Next';
		$config['prev_link'] = 'Prev';
		$config['cur_tag_open'] = '<b>';
		$config['cur_tag_close'] = '</b>';
		$this->pagination->initialize($config);

		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $this->view_data['book_categories'] = $this->ml->fetch_categories($config["per_page"], $page);
        $this->view_data["links"] = $this->pagination->create_links();
	}
	
	public function add_books()
	{
		$this->view_data['system_message'] = $this->_msg();
		$this->load->model('M_librarian','ml');
		$this->load->model('M_media_types','mt');
		$this->view_data['categories'] = $this->ml->get_category_array();
		$this->view_data['media_types'] = $this->mt->get_for_dd(array('id','media_type'), false, '--SELECT TYPES--', 'media_type');
		
		if($this->input->post('add_book'))
		{	
			$this->form_validation->set_rules('book[accession_number]','Accession Number','required|trim|htmlspecialchars|is_unique[library_books.accession_number]');
			$this->form_validation->set_rules('book[call_number]','Call Number','required|trim|htmlspecialchars');
			$this->form_validation->set_rules('book[book_name]','Item Name','required|trim|htmlspecialchars');
			$this->form_validation->set_rules('book[book_desc]','Item Description','required|trim|htmlspecialchars');
			$this->form_validation->set_rules('book[book_isbn]','Item ISBN Number','required|trim|htmlspecialchars|alpha_dash');
			$this->form_validation->set_rules('book[book_barcode]','Bar Code','trim|htmlspecialchars|alpha_dash');
			$this->form_validation->set_rules('book[book_author]','Item Author','required|trim|htmlspecialchars');
			$this->form_validation->set_rules('book[book_publisher]','Item Publisher','required|trim|htmlspecialchars');
			$this->form_validation->set_rules('book[book_dop]','Date published','required|trim|htmlspecialchars|callback__mdf');
			$this->form_validation->set_rules('book[book_category]','Item Subject','required|trim|htmlspecialchars');
			$this->form_validation->set_rules('book[media_type_id]','Item Type','required|trim|htmlspecialchars');
			$this->form_validation->set_rules('book[book_copies]','Item No of Copies','required|numeric|trim|htmlspecialchars');
		
			if($this->form_validation->run() !== FALSE)
			{			
				if($this->ml->add_books($this->input->post('book')))
				{
					$this->_msg('s','Book was successfully added.','librarian/add_books');
				}else{
					$this->view_data['system_message'] = $this->_msg('e','Unable to add book to database.');
				}
			}
		}
	}
	
	public function addcat($id = false)
	{
		$this->view_data['system_message'] = $this->session->flashdata('system_message');
		$this->load->model('M_library_book_category','mc');

		if($id){

			$this->view_data['categories'] = $this->mc->get($id);
			if($this->input->post('add_category'))
			{
				$this->form_validation->set_rules('cat[cat_name]','Subject Name','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('cat[cat_desc]','Subject Description','trim|htmlspecialchars');
			
				if($this->form_validation->run() !== FALSE)
				{
					
					unset($data);
					$data['lbc_name'] = $this->input->post('cat')['cat_name'];
					$data['lbc_desc'] = $this->input->post('cat')['cat_desc'];
					$rs = $this->mc->update($id, $data); 

					if($rs)
					{
						$this->_msg('s','Subject was updated successfully.', current_url());
					}else{
						$this->view_data['system_message'] = $this->_msg('e','Unable to update subject.');
					}
				}
			}

		}else{
			if($this->input->post('add_category'))
			{
				$this->form_validation->set_rules('cat[cat_name]','Subject Name','required|is_unique[library_book_category.lbc_name]|trim|htmlspecialchars');
				$this->form_validation->set_rules('cat[cat_desc]','Subject Description','trim|htmlspecialchars');
				$this->form_validation->set_message('is_unique','That %s is Already Taken');
			
				if($this->form_validation->run() !== FALSE)
				{
					$this->load->model('M_librarian','ml');
					if($this->ml->add_category($this->input->post('cat')))
					{
						$this->_msg('s','Subject was added successfully.','librarian/addcat');
					}else{
						$this->view_data['system_message'] = $this->_msg('e','Unable to add subject.');
					}
				}
			}
		}
	}

	public function delcat($id = false)
	{
		$this->view_data['system_message'] = $this->session->flashdata('system_message');
		$this->load->model('M_library_book_category','mc');

		if($id){

			$cat = $this->mc->get($id);
			if(!$cat){ show_404(); }
			$rs = $this->mc->delete($id);
			if($rs)
			{
				$this->_msg('s','Subject was deleted successfully.', 'librarian/categories');
			}else{
				$this->_msg('e','Unable to delete subject.', 'librarian/categories');
			}

		}else{ show_404(); }
	}
	
	public function update_book($id = FALSE)
	{
		$this->view_data['system_message'] = $this->_msg();
		if(is_numeric($id))
		{
			$this->load->model('M_librarian','ml');
			$this->load->model('M_media_types','mt');
			$this->view_data['media_types'] = $this->mt->get_for_dd(array('id','media_type'), false, '--SELECT TYPES--', 'media_type');
			$this->view_data['categories'] = $this->ml->get_category_array();
			$this->view_data['book_profile'] = $this->ml->get_book_profile($id);
			$this->view_data['book_id'] = $id;
			if($this->input->post('update_book'))
			{
				$this->form_validation->set_rules('book[accession_number]','Accession Number','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('book[call_number]','Call Number','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('book[book_name]','Item Name','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('book[book_desc]','Item Description','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('book[book_isbn]','Item ISBN Number','required|trim|htmlspecialchars|alpha_dash');
				$this->form_validation->set_rules('book[book_barcode]','Bar Code','trim|htmlspecialchars|alpha_dash');
				$this->form_validation->set_rules('book[book_author]','Item Author','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('book[book_publisher]','Item Publisher','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('book[book_dop]','Date published','required|trim|htmlspecialchars|callback__mdf');
				$this->form_validation->set_rules('book[book_category]','Item Subject','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('book[media_type_id]','Item Type','required|trim|htmlspecialchars');
				$this->form_validation->set_rules('book[book_copies]','Item No of Copies','required|numeric|trim|htmlspecialchars');
			
			
				if($this->form_validation->run() !== FALSE)
				{			
					if($this->ml->update_book($this->input->post('book'),$id))
					{
						$this->_msg('s','Book was successfully updated.','librarian/update_book/'.$id.'');
					}else{
						$this->view_data['system_message'] = $this->_msg('e','Unable to update book.');
					}
				}
			
			
			
			
			
			
			
			}
		

		}else{
			redirect('librarian');
		}
	}

	///////////////////////////////////
	// BOOK / MEDIA TYPES /////////////
	///////////////////////////////////

	public function media_types($page = 0)
	{
		$this->load->model('M_media_types');

		
		//PAGINATION
		$this->view_data['system_message'] = $this->session->flashdata('system_message');
		
		$like = false;
		$filter = false;
		
		// if($_GET)
		// {
		// 	if(isset($_GET['sc_id']) && trim($_GET['sc_id']) != ""){
		// 		$this->view_data['sc_id'] = $sc_id = trim($_GET['sc_id']);
		// 		$like['subjects.sc_id'] = $sc_id;
		// 	}	
		// }
		
		//CONFIGURATION
		// $get['fields'] = array('*');
		
		$get['where'] = $filter;
		$get['like'] = $like;
		$get['order'] = "media_type";
		$get['all'] = true; //GET ALL EXCLUDE LIMIT
		$get['count'] = true; //RETURN COUNT NOT ROW
		$get['array'] = false; //RETURN OBJECT NOT ARRAY
		$get['single'] = false; //RETURN ALL NOT SINGLE
		
	
		$this->load->library("pagination");
		$this->_init_pagnate_config();
		$config = $this->pagnate_config;
		$config["base_url"] = base_url() ."librarian/media_types";
		$suffix = '?'.http_build_query($_GET, '', "&");
		$suffix = str_replace("&submit=Search", "", $suffix);
		$this->view_data['get_url'] = $config['suffix'] = $suffix;
		$config['first_url'] = $config['base_url'].$config['suffix']; 
		
		$this->view_data['total_rows'] = $config["total_rows"] = $this->M_media_types->get_record(false, $get);
		
		$config["per_page"] = 30;
		$config['num_links'] = 10;
		$config["uri_segment"] = 3;
		// $config['use_page_numbers'] = TRUE;
		$this->pagination->initialize($config);
		
		//FOR PAGINATION
		$get['all'] = false;
		$get['count'] = false;
		
		$config['start'] = $page;
		$config['limit'] = $config['per_page'];
		
		$get['start'] = $page;
		$get['limit'] = $config['per_page'];
		
		$this->view_data['media_types'] = $search = $this->M_media_types->get_record(false, $get);
		$this->view_data['links'] = $this->pagination->create_links();
	
	}

	public function add_media_types($id = false, $action = false)
	{
		$this->view_data['system_message'] = $this->session->flashdata('system_message');

		$this->load->model('M_media_types');

		if($id){
			$this->view_data['media_types'] = $mt = $this->M_media_types->get($id);

			if($action === "delete"){
				$rs = $this->M_media_types->delete($id);
				if($rs){
					$this->_msg('s','Media type was deleted successfully.','librarian/media_types');
				}else{
					$this->_msg('e','Unable to delete media type.','librarian/media_types');
				}
			}
		}

		if($this->input->post('save_type'))
		{
			$data = $this->input->post('type');

			if($id){ if($data['media_type'] === $mt->media_type){ return true; } }

			$this->form_validation->set_rules('type[media_type]','Media Type','required|is_unique[media_types.media_type]|trim|htmlspecialchars');
			
			if($this->form_validation->run() !== FALSE)
			{

				if($id){

					if((object)$this->M_media_types->update($id, $data)->status){
						$this->_msg('s','Media Type was updated successfully.',current_url());
					}else{
						$this->_msg('e','Unable to edit media type.',current_url());
					}

				}else{

					if((object)$this->M_media_types->insert($data)->status){
						$this->_msg('s','Media Type was added successfully.',current_url());
					}else{
						$this->_msg('e','Unable to add media type.',current_url());
					}
				}
			}
		}
	}

	///////////////////////////////////
	// END OF BOOK / MEDIA TYPES //////
	///////////////////////////////////
	
}